import React, {useContext} from 'react';
import {View, Image, Alert, Platform, PermissionsAndroid} from 'react-native';
import dayjs from 'dayjs';
import Toast from 'react-native-root-toast';
import {useNavigation} from '@react-navigation/native';
import {useMount, useSafeState} from 'ahooks';
import {Button, Text, ListItem, Avatar} from '@rneui/base';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {useSelector, useDispatch} from 'react-redux';
import GlobalContext from '@/GlobalContext';
import ImagePicker from 'react-native-image-crop-picker';
import fileExtension from 'file-extension';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
const leftIconSize = 18;
const rightIconSize = 20;

import RNFS from 'react-native-fs';
import putFileToOss from '@/fun/putFileToOss';

export default () => {
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  let defaultUri = accountInfo?.j_ext_info?.photo_relative_path;
  if (defaultUri) {
    defaultUri = `${OssHost}/${defaultUri}`;
  }

  const [submitLoading, setSubmitLoading] = useSafeState(false);
  const [uri, setUri] = useSafeState(defaultUri);
  const submit = async ({ossRelativePath}) => {
    setSubmitLoading(true);
    try {
      let rsObj = undefined;
      try {
        const reqFormData = {
          photo_relative_path: ossRelativePath,
        };
        let res = await fetch(`${ApiHost}/account/json/save-account-info`, {
          headers: {
            'content-type': 'application/json',
            token: token,
          },
          method: 'POST',
          body: JSON.stringify(reqFormData),
        });
        rsObj = await res.json();
        setSubmitLoading(false);
      } catch (e) {
        setSubmitLoading(false);
        Alert.alert('操作失败', e.message);
        return;
      }
      if (!rsObj) {
        Alert.alert('操作失败', '!rsObj');
        return;
      }
      const {code = 0, msg} = rsObj || {};
      if (code <= 0) {
        Alert.alert('操作失败', msg);
        return;
      }

      dispatch(setKeyGetAccountInfo(Math.random()));

      let toast = Toast.show(msg, {
        // duration: Toast.durations.LONG,
        duration: 1000,
        // position: Toast.positions.CENTER,
        position: 150,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0,
        onShow: () => {
          // calls on toast\`s appear animation start
        },
        onShown: () => {
          // calls on toast\`s appear animation end.
        },
        onHide: () => {
          // calls on toast\`s hide animation start.
        },
        onHidden: () => {
          // calls on toast\`s hide animation end.
        },
      });
    } catch (e) {
      Alert.alert('系统繁忙', '操作失败');
    }
  };

  const openCamera = async () => {
    try {
      const obj = await ImagePicker.openPicker({
        width: 100,
        height: 100,
        cropping: true,
      });
      const localFilePath = obj.path;
      const fileName =
        dayjs().format('YYYYMMDDHHmmss') + '.' + fileExtension(localFilePath);

      const file = {
        uri: localFilePath,
        type: 'multipart/form-data',
        name: obj.fileName,
      };

      setSubmitLoading(true);
      const uploadObj = await putFileToOss({
        token,
        fileName,
        file,
      });
      console.log('uploadObj', uploadObj);
      const {ossRelativePath} = uploadObj || {};
      const newUrl = `${OssHost}/${ossRelativePath}`;
      console.log('newUrl', newUrl);
      setUri(newUrl);

      submit({ossRelativePath});
    } catch (e) {
      console.log('异常', e.message);
    }
  };

  const checkPower = () => {
    // 从相机中选择
    if (Platform.OS === 'android') {
      PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA).then(
        res => {
          if (res !== 'granted') {
            Alert.alert(
              '相机权限没打开',
              '请在手机的“设置”选项中,允许访问您的摄像头和麦克风',
            );
          } else {
            openCamera();
          }
        },
      );
    } else {
      openCamera();
      // if (Camera) {
      //   Camera.checkDeviceAuthorizationStatus().then(access => {
      //     if (!access) {
      //       Alert.alert(
      //         '相机权限没打开',
      //         '请在iPhone的“设置-隐私”选项中,允许访问您的摄像头和麦克风',
      //       );
      //     } else {
      //       openCamera();
      //     }
      //   });
      // }
    }
  };
  return (
    <>
      <ListItem
        onPress={checkPower}
        style={{
          marginTop: 1,
        }}>
        <Text>头像</Text>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-end',
            flex: 1,
            minHeight: 60,
          }}>
          {uri && (
            <Avatar
              size={42}
              rounded={false}
              source={{uri: uri}}
              title={uri ? '' : '头像'}
              titleStyle={{fontSize: 12}}
              containerStyle={{backgroundColor: '#999', borderRadius: 8}}
              avatarStyle={{borderRadius: 8}}
            />
          )}
        </View>
        <ListItem.Chevron size={rightIconSize} />
      </ListItem>
    </>
  );
};
